//
//  AppiCloud.m
//  Personal Passlock
//
//  Created by 杨岑 on 5/6/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "AppiCloud.h"

static AppiCloud* _singleton = nil;

@implementation AppiCloud
{
    BOOL _initCalled;
}

#pragma mark Singleton

+ (instancetype)singleton
{
    @synchronized(self)
    {
        if (!_singleton)
        {
            _singleton = [[AppiCloud alloc] init];
        }
    }
    return _singleton;
}

+ (instancetype)instance
{
    @synchronized(self)
    {
        if (!_singleton)
        {
            _singleton = [[AppiCloud alloc] init];
        }
    }
    return _singleton;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self)
    {
        if (!_singleton) _singleton = [super allocWithZone:zone];
    }
    return _singleton;
}

- (instancetype)init
{
    @synchronized(self)
    {
        if (!_initCalled)
        {
            self = [super init];
            if (self != nil)
            {
                _localDocsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            }
            _initCalled = YES;
        }
    }
    
    return self;
}


#pragma mark Methods

- (id)iCloudToken
{
    return [NSFileManager defaultManager].ubiquityIdentityToken;
}

- (BOOL)setupiCloud:(void (^)(BOOL))handler
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error;
        NSFileManager* fm = [NSFileManager defaultManager];
        _baseURL = [fm URLForUbiquityContainerIdentifier:nil];
        if (_baseURL)
        {
            _docsURL = [_baseURL URLByAppendingPathComponent:@"Documents"];
            
            NSLog(@"iCloud URL: %@", self.baseURL);
            NSLog(@"iCloud URL: %@",self.docsURL);
            
            BOOL isDir;
            if (![fm fileExistsAtPath:_docsURL.path isDirectory:&isDir])
            {
                [fm createDirectoryAtURL:_docsURL withIntermediateDirectories:NO attributes:nil error:&error];
                if (error)
                {
                    NSLog(@"Could not initialize iCloud container: %@", error);
                }
            }
        }
        handler(_baseURL != nil);
    });
    
    return YES;
}

- (NSURL *)formatDocURL:(NSString *)docName
{
    return [_docsURL URLByAppendingPathComponent:docName];
}

- (NSString*)formatLocalDocPath:(NSString *)docName
{
    return [_localDocsDir stringByAppendingPathComponent:docName];
}

@end
